import 'dart:math';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:gw_github_flutter/common/global.dart';
import 'package:gw_github_flutter/common/route_name.dart';
import 'package:gw_github_flutter/generated/l10n.dart';
import 'package:gw_github_flutter/models/index.dart';
import 'package:gw_github_flutter/tools/gwEasyRefrashManager.dart';
import 'package:scroll_to_index/scroll_to_index.dart';
import 'package:sticky_and_expandable_list/sticky_and_expandable_list.dart';

class SliverRouteTableView extends StatefulWidget {
  SliverRouteTableView({Key? key}) : super(key: key);

  @override
  State<SliverRouteTableView> createState() => _SliverRouteTableViewState();
}

class _SliverRouteTableViewState extends State<SliverRouteTableView> {
  var list = Global.getTBSectionsList();
  var list2 = Global.getTBSectionsList();
  late AutoScrollController scrollController;
  // late EasyRefreshController _controller;
  int counter = 10;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    list2.removeRange(3, list.length);
    scrollController = AutoScrollController(
        viewportBoundaryGetter: () =>
            Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: Axis.vertical);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            RouteName.sliverRoute_tableView,
            style: TextStyle(fontSize: 14),
          ),
        ),
        floatingActionButton: InkWell(
          onTap: () {
            _scrollToIndex();
          },
          child: Container(
            height: 48,
            width: 50,
            // padding: EdgeInsets.all(10),
            alignment: Alignment.center,
            color: Colors.blueGrey,
            child: Text(
              "Click Me:",
              style: TextStyle(color: Colors.white),
            ),
          ),
        ),
        body: EasyRefresh.builder(
            header: GwEasyRefrashManager.setRefrashHeader(
                mainAxisAlignment: MainAxisAlignment.end),
            onRefresh: () async {
              await Future.delayed(const Duration(seconds: 2));
              if (!mounted) {
                return;
              }
              setState(() {
                list = list2;
              });
            },
            onLoad: () async {
              await Future.delayed(const Duration(seconds: 2));
              if (!mounted) {
                return;
              }
              setState(() {
                list += list2;
              });
            },
            childBuilder: (context, physics) {
              return CustomScrollView(
                physics: physics,
                controller: scrollController,
                slivers: [
                  const HeaderLocator.sliver(
                    clearExtent: true,
                  ),
                  // Expanded(
                  //   child:
                  SliverExpandableList(
                    // physics: physics,
                    // controller: scrollController,
                    builder: SliverExpandableChildDelegate<dynamic,
                            TbSectionModel>(
                        // sticky: false,
                        // overlapsContent: false,
                        sectionList: list,
                        headerBuilder: (context, sectionIndex, index) {
                          TbSectionModel item = list[sectionIndex];
                          // if (sectionIndex % 2 == 0) {
                          //   return SizedBox.shrink();
                          // } else {
                          return GestureDetector(
                            child: Container(
                                color: Colors.lightBlue,
                                height: 100,
                                padding: EdgeInsets.only(left: 20),
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  item.header ?? "",
                                  style: TextStyle(color: Colors.white),
                                )),
                            onTap: () {
                              setState(() {
                                item.setSectionExpanded(
                                    !item.isSectionExpanded());
                              });
                            },
                          );
                          // }
                        },
                        itemBuilder: (context, sectionIndex, itemIndex, index) {
                          String item = list[sectionIndex].items?[itemIndex];
                          return _wrapScrollTag(
                              index: index, child: _cellTwo(item, index));
                        },
                        separatorBuilder: (context, isSectionSeparator, index) {
                          return isSectionSeparator
                              ? SizedBox(
                                  height: 15,
                                )
                              : Container();
                        }),
                  ),
                  const FooterLocator.sliver()
                ],
              );
            }));
  }

  Widget _cellTwo(String item, int index) {
    if (index % 2 == 0) {
      return Container(
        color: Colors.green,
        height: 70,
      );
    } else {
      return Container(
        color: Colors.yellow,
        height: 50,
      );
    }
  }

  Future _scrollToIndex() async {
    setState(() {
      counter = Random().nextInt(20);
    });
    await scrollController.scrollToIndex(counter,
        preferPosition: AutoScrollPosition.begin);
    scrollController.highlight(counter);
  }

  Widget _wrapScrollTag({required int index, required Widget child}) =>
      AutoScrollTag(
        key: ValueKey(index),
        controller: scrollController,
        index: index,
        child: child,
        highlightColor: Colors.black.withOpacity(0.1),
      );
}
